package com.luomu.base.control.cookBook.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.luomu.base.api.bo.RspPage;
import com.luomu.base.api.cookBook.simple.bo.FinanceArApAndInvoiceInfoBO;
import com.luomu.base.api.cookBook.excel.bo.FinanceArApAndInvoiceInfoExcelBO;
import com.luomu.base.api.cookBook.simple.bo.FinanceArApAndInvoiceInfoReqBO;
import com.luomu.base.api.cookBook.simple.service.FinanceArApAndInvoiceInfoService;
import com.luomu.base.control.cookBook.excel.utils.EasyExcelAndSheetUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/apis/excelExport")
public class ExcelExportController {
    protected Logger log = LoggerFactory.getLogger(ExcelExportController.class);


    @Autowired
    private HttpServletResponse response;

    @Autowired
    private FinanceArApAndInvoiceInfoService financeArApAndInvoiceInfoService;

    /**
     * 应付挂帐单模板下载
     */
    @PostMapping(value = "/excelTemplateDownload")
    public void excelTemplateDownload() {
        String fileName = "应付挂帐单";
        ClassPathResource resource = new ClassPathResource("template/应付挂帐单.xlsx");
        try {
            EasyExcelAndSheetUtils.writeExcelTemplate(response, fileName, resource.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据导出 通过excelBO
     */
    @RequestMapping(value = "/financeArApAndInvoiceInfoExportByExcelBO", method = RequestMethod.POST)
    public void financeArApAndInvoiceInfoExportByExcelBO(@RequestBody FinanceArApAndInvoiceInfoReqBO reqBO) {
        RspPage<FinanceArApAndInvoiceInfoBO> financeArApAndInvoiceInfoBORspPage =  financeArApAndInvoiceInfoService.queryFinanceArApAndInvoiceInfoList(reqBO);
        List<FinanceArApAndInvoiceInfoBO> list = financeArApAndInvoiceInfoBORspPage.getRows();
        log.info("导出属性值/queryClassifyWithPropExport查询结果："+ JSON.toJSONString(list));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        int number = (int) (Math.random() * 90 + 10);
        String fileName = "应收挂帐单_" + simpleDateFormat.format(new Date())+"_"+number;
        try {
            // FinanceArApAndInvoiceInfoExcelBO 是excel的bo
            EasyExcelAndSheetUtils.writeExcel(response, list, fileName, FinanceArApAndInvoiceInfoExcelBO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据导出 通过excelBO 并设置excel 的样式
     */
    @RequestMapping(value = "/financeArApAndInvoiceInfoExportByExcelBOOfStyle", method = RequestMethod.POST)
    public void financeArApAndInvoiceInfoExportByExcelBOOfStyle(@RequestBody FinanceArApAndInvoiceInfoReqBO reqBO) {
        RspPage<FinanceArApAndInvoiceInfoBO> financeArApAndInvoiceInfoBORspPage =  financeArApAndInvoiceInfoService.queryFinanceArApAndInvoiceInfoList(reqBO);
        List<FinanceArApAndInvoiceInfoBO> list = financeArApAndInvoiceInfoBORspPage.getRows();
        log.info("导出属性值/queryClassifyWithPropExport查询结果："+ JSON.toJSONString(list));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        int number = (int) (Math.random() * 90 + 10);
        String fileName = "应收挂帐单_" + simpleDateFormat.format(new Date())+"_"+number;
        try {
            EasyExcelAndSheetUtils.writeExcelOfStyle(response, list, fileName, FinanceArApAndInvoiceInfoExcelBO.class,EasyExcelAndSheetUtils.defaultStyles());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出入库单明细 通过excel模板
     */
    @PostMapping(value = "/financeArApAndInvoiceInfoExportByTemplate")
    public void financeArApAndInvoiceInfoExportByTemplate(@Valid @RequestBody FinanceArApAndInvoiceInfoReqBO reqBo) {
        RspPage<FinanceArApAndInvoiceInfoBO> financeArApAndInvoiceInfoBORspPage =  financeArApAndInvoiceInfoService.queryFinanceArApAndInvoiceInfoList(reqBo);
        List<FinanceArApAndInvoiceInfoBO> list = financeArApAndInvoiceInfoBORspPage.getRows();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        int number = (int) (Math.random() * 90 + 10);
        String fileName = "应付挂帐单_" + simpleDateFormat.format(new Date())+"_"+number;
        OutputStream out = null;
        try {
            ClassPathResource resource = new ClassPathResource("template/应付挂帐单.xlsx");
            EasyExcelAndSheetUtils.writeExcelByTemplate(response, list, fileName, resource.getInputStream());
        } catch (Exception e) {
            log.error("导出入库单异常",e);
        }
    }



    /**
     * 导出入库单明细  最后一行添加汇总数据
     */
    @PostMapping(value = "/financeArApAndInvoiceInfoLastRowExport")
    public void financeArApAndInvoiceInfoLastRowExport(@Valid @RequestBody FinanceArApAndInvoiceInfoReqBO reqBo) {
        RspPage<FinanceArApAndInvoiceInfoBO> financeArApAndInvoiceInfoBORspPage =  financeArApAndInvoiceInfoService.queryFinanceArApAndInvoiceInfoList(reqBo);
        List<FinanceArApAndInvoiceInfoBO> list = financeArApAndInvoiceInfoBORspPage.getRows();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        int number = (int) (Math.random() * 90 + 10);
        String fileName = "应收挂帐单_" + simpleDateFormat.format(new Date())+"_"+number;
        OutputStream out = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel"); // .xlsx
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//开放权限，让前端获取到
            out = response.getOutputStream();

            ClassPathResource resource = new ClassPathResource("template/应付挂帐单.xlsx");
            ExcelWriter excelWriter = EasyExcel.write(out).withTemplate(resource.getInputStream()).excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            //多行数据填充
            excelWriter.fill(list,fillConfig, writeSheet);

            //最后汇总行设置
            FinanceArApAndInvoiceInfoBO financeArApAndInvoiceInfoItemBO = new FinanceArApAndInvoiceInfoBO();
            List<List<String>> totalListList = new ArrayList<List<String>>();
            List<String> totalList = new ArrayList<String>();
            totalList.add("汇总");
            totalList.add(financeArApAndInvoiceInfoItemBO.getInvoiceCode());
            // 增加最后一行汇总的数据
            totalListList.add(totalList);
            excelWriter.write(totalListList, writeSheet);


            out.flush();
            excelWriter.finish();
        } catch (Exception e) {
            log.error("导出入库单异常",e);
        }finally {
            try{
                if(out != null){
                    out.close();
                }
            }catch (Exception ex){
                log.error("导出入库单-关闭流异常",ex);
            }
        }
    }
}
